'use strict';

const _ = require('lodash');
const Controller = require('egg').Controller;

class CollectController extends Controller {

  /*
  * 展示用户收藏的文章列表
  */
  async listCollectedTopics() {
    console.time('listCollectedTopics');
    const {ctx, service} = this;
    const user_name = ctx.params.name;
    const current_page = Number(ctx.query.page) || 1;
    const page_size = 50;
    const kw = ctx.request.query.kw || '';
    const tag_name = ctx.request.query.tag_name;
    const ua = this.ctx.headers['user-agent'].toLocaleLowerCase();

    let pageTitle;
    let is_oneself;
    if (ctx.user && ctx.user.nickname == user_name) {
      pageTitle = '我的收藏';
      is_oneself = true;
    } else {
      pageTitle = `${user_name}的收藏`;
      is_oneself = false;
    }

    const user = await service.userSvc.getUserByLoginName(user_name);
    if (!user) {
      ctx.status = 404;
      ctx.message = '这个用户不存在。';
      return;
    }
    const user_id = user._id;


    let my_collect_tags;


    if (ctx.user && ctx.user.loginname == user_name) {
      [my_collect_tags] = await Promise.all([
        service.topicCollectSvc.listTags(user_id)
      ]);
    }

    let is_attention = false;
    if (this.ctx.user && this.ctx.user.followings.map(v => v.name).includes(user.loginname)) {
      is_attention = true;
    }

    let locals = {
      currentUser: this.ctx.user,
      is_attention,
      current_page,
      user,
      kw,
      my_collect_tags: my_collect_tags,
      tag_name: tag_name,
      order_by: 'collect_at',
      pageTitle,
      url: '/collectionsScroll',
      params: JSON.stringify({name: user.loginname, kw, tag_name})
    };


    await ctx.renderX('user/collect_topics.nj', locals);
    console.timeEnd('listCollectedTopics');
  }


  /*
* 展示用户收藏的文章列表
*/
  async listCollectedTopicsScroll() {
    const {ctx, service} = this;
    const user_name = ctx.query.name;
    const current_page = Number(ctx.query.page) || 1;
    const page_size = this.config.list_topic_count;
    const kw = ctx.request.query.kw || '';
    const tag_name = ctx.request.query.tag_name;


    const user = await service.userSvc.getUserByLoginName(user_name);
    if (!user) {
      ctx.status = 404;
      ctx.message = '这个用户不存在。';
      return;
    }
    const user_id = user._id;


    let is_oneself;
    if (ctx.user && ctx.user.nickname == user_name) {
      is_oneself = true;
    } else {
      is_oneself = false;
    }


    let topics = await service.topicCollectSvc.listCollectedTopics(user_id, is_oneself, kw, tag_name, current_page, page_size);


    for (const topic of topics) {
      topic.pic = null;
    }


    const html = await Promise.all(topics.map(topic => {
      const ua = ctx.get('user-agent');
      if (ctx.helper.isMobile(ua)) {
        // 如果是移动设备...
        return ctx.renderView('mobile/topic/abstract_mobile.nj', {topic, layout: false});
      } else {
        // 如果不是移动设备...
        return ctx.renderView('pc/topic/abstract_pc_simple.nj', {topic, layout: false});
      }
    }));

    ctx.body = html.join('');
  }


  /**
   * 收藏文章
   * topic_id: 文章id,
   * collect_tags: 标签array,
   * user_id: 用户id
   *
   */
  async collect() {
    const {ctx, service} = this;
    const topic_id = ctx.request.body.topic_id;
    const collect_tags = ctx.request.body.collect_tags;
    const user_id = ctx.user._id;
    const brief = ctx.request.body.brief || '';

    const topic = await service.topicSvc.getTopic(topic_id);

    if (!topic) {
      ctx.body = {status: 'failed'};
      return;
    }

    if (topic.author_id.toString() == user_id.toString()) {
      topic.intro = brief;
      await topic.save();
    }

    // 收藏和标签的相关业务
    await service.topicCollectSvc.upsert(ctx.user._id, topic._id, topic.title, brief, topic.is_public, topic.original_url, collect_tags);

    ctx.body = {status: 'success'};

    await Promise.all([
      service.userSvc.incrementCollectTopicCount(ctx.user._id),
      service.topicSvc.incrementCollectCount(topic_id),
    ]);
  }

  /**
   * 取消收藏文章
   * topic_id: 文章id,
   * user_id: 用户id
   */
  async de_collect() {
    const {ctx, service} = this;
    const topic_id = ctx.request.body.topic_id;
    const user_id = ctx.user._id;

    const topic = await service.topicSvc.getTopic(topic_id);

    if (!topic) {
      ctx.body = {status: 'failed'};
      return;
    }

    const removeResult = await service.topicCollectSvc.remove(
      ctx.user._id,
      topic._id
    );

    if (removeResult.n === 0) {
      ctx.body = {status: 'failed', error_msg: '已经没有收藏此文章'};
      return;
    }

    ctx.body = {status: 'success'};

    await Promise.all([
      service.userSvc.decrementCollectTopicCount(ctx.user._id),
      service.topicSvc.decrementCollectCount(topic_id),
    ]);
  }


  /**
   * 修改标签名
   * @param {string} user_id 用户id
   * @param {string} old_name 原标签名
   * @param {string} new_name 新标签名
   */
  async updateTagName() {
    const {ctx, service} = this;
    const user_id = ctx.user._id;
    const old_name = ctx.request.body.old_name;
    const new_name = ctx.request.body.new_name;

    await service.topicCollectSvc.updateTagName(user_id, old_name, new_name);
    ctx.body = {status: 'success'};
  }

  /**
   * 删除标签
   * id: 标签id,
   * user_id: 用户id
   */
  async removeTag() {
    const {ctx, service} = this;
    const user_id = ctx.user._id;
    const name = ctx.request.body.name;

    await service.topicCollectSvc.removeTag(user_id, name);
    ctx.body = {status: 'success'};
  }


  /**
   * 展示用户所有标签及标签包含文章的数量
   * user_id: 用户id
   */
  async listTags() {
    const {ctx, service} = this;
    const user_id = ctx.user._id;

    let result = await service.topicCollectSvc.listTags(user_id);
    ctx.body = {status: 'success', data: result};
  }

  /**
   * 展示用户收藏此篇文章时分配的标签
   * topic_id: 文章id
   * user_id: 用户id
   */
  async listTagsOnTopic() {
    const {ctx, service} = this;
    const topic_id = ctx.request.query.topic_id;
    const user_id = ctx.user._id;

    let topicCollect = await service.topicCollectSvc.getTopicCollect(user_id, topic_id);
    let tags = [];
    if (topicCollect && topicCollect.tags) {
      tags = topicCollect.tags.map((v) => {
        return {name: v}
      });
    }

    let is_collected;
    let brief;
    if (topicCollect) {
      brief = topicCollect.brief || '';
      is_collected = true;
    } else {
      brief = '';
      is_collected = false;
    }

    ctx.body = {status: 'success', data: {is_collected: is_collected, brief: brief, tags: tags}};
  }

  /**
   * 快速收藏
   * content: 收藏链接
   * is_public: 是否公开
   */
  async simpleCollect() {
    const {ctx, service} = this;

    let content = ctx.request.body.content;
    if (!content) {
      return {status: 404, message: '链接地址不能为空'};
    }

    const user_id = ctx.user._id;
    const is_public = ctx.request.body.is_public;
    const brief = ctx.request.body.brief;
    let tags = ctx.request.body.tags;
    let title = ctx.request.body.title;
    if (!title) {
      let realInfo = await service.searchSvc.findTitleAndUrl(content);
      title = realInfo.finalTitle;
      content = realInfo.finalUrl;
    }
    const tab = 'share';
    const original_url = content;


    // 储存新文章
    const topic = await service.topicSvc.upsert(title, content, tab, user_id, original_url, is_public, brief, null);
    const topic_id = topic._id;

    await Promise.all([
      service.topicCollectSvc.upsert(user_id, topic_id, title, brief, is_public, original_url, tags),
      service.userSvc.incrementCollectTopicCount(user_id),
      service.topicSvc.incrementCollectCount(topic_id),
      service.userSvc.incrementScoreAndTopicCount(topic.author_id, 3, 0),
    ]);


    await this.ctx.helper.notifySuperAdmin(user_id, topic_id);

    ctx.body = {status: 'success', message: '收藏成功'};
  }

}

module.exports = CollectController;
